# == Coding: UTF-8 ==
# @Project :        DormitoryManagementSystem
# @fileName         login.py  
# @version          v0.5
# @author           16980
# @GiteeWarehouse   https://gitee.com/liu-long068/
# @WritingTime      2023/5/1 0001
# @Software:        PyCharm
# ====/******/=====
import json
import hashlib

from public.menus.menu import Menu


class Login:
    def __init__(self):
        self.path = r'D:\BooksManagementSystem\public\users\users.json'
        self.username = None
        self.password = None
        self.users = []
        self.load_users()


    def load_users(self):
        # 先读取已有的 JSON 文件
        try:
            with open(self.path, 'r') as file:
                self.users = json.load(file)
        except (FileNotFoundError, json.JSONDecodeError) as e:
            print(f'Error loading user data: {e}')

    def save_users(self):
        try:
            with open(self.path, 'w') as file:
                json.dump(self.users, file, indent=4)
        except FileNotFoundError as e:
            print(f'Error saving user data: {e}')

    def login_business(self):
        self.username = str(input('请输入用户名：'))
        self.password = str(input('请输入密码：'))
        # 将密码进行哈希加密后进行匹配
        hashed_password = hashlib.sha256(self.password.encode()).hexdigest()
        self.load_users()

        for user in self.users:
            if user['username'] == self.username:

                if user['password'] == hashed_password:
                    print(f"用户{self.username}登录成功！")
                    menu = Menu()
                    menu.admin_menu()
                    return user['flag']
                else:
                    print("密码错误！")
                    return False
        print("用户名不存在！")
        return False

